//
//  FMDBTools.m
//  数据存储方式(FMDB)
//
//  Created by whz on 17/3/1.
//  Copyright © 2017年 whz. All rights reserved.
//

#import "FMDBTools.h"
#import "Student.h"
#import <FMDB.h>

#define KSQLNAME @"stuModel.sqlite"

@implementation FMDBTools

static FMDatabase *_fmdb;

+ (void)initialize {

    NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingString:KSQLNAME];
    _fmdb = [FMDatabase databaseWithPath:filePath];
    [_fmdb open];
    
    [_fmdb executeUpdate:@"CREATE TABLE IF NOT EXISTS t_stuModel(id INTEGER PRIMARY KEY, name TEXT NOT NULL, age INTEGER NOT NULL, numberId TEXT NOT NULL);"];
}

+ (BOOL)insertModel:(Student *)stuModel {

    NSString *insertSql = [NSString stringWithFormat:@"INSERT INTO t_stuModel(name, age, numberId) VALUES ('%@', '%@', '%@');", stuModel.name, stuModel.age, stuModel.numberId];
    return [_fmdb executeUpdate:insertSql];
}

+ (NSArray *)queryData:(NSString *)querySql {

    if (querySql == nil) {
        querySql = @"SELECT * FROM t_stuModel;";
    }
    
    NSMutableArray *arrM = [NSMutableArray array];
    FMResultSet *set = [_fmdb executeQuery:querySql];
    
    while ([set next]) {
        
        NSInteger idx = [set intForColumn:@"id"];
        NSString *name = [set stringForColumn:@"name"];
        NSString *age = [set stringForColumn:@"age"];
        NSString *numberId = [set stringForColumn:@"numberId"];
        
        Student *stuModel = [Student modelWithId:idx Name:name age:age no:numberId];
        [arrM addObject:stuModel];
    }
    return arrM;
}

+ (BOOL)modifyData:(Student *)modifySqlStuModel {
    
    NSString *updateStr = [NSString stringWithFormat:@"UPDATE t_stuModel SET name = '%@', age = '%@', numberId = '%@' WHERE id = '%zd';",modifySqlStuModel.name, modifySqlStuModel.age, modifySqlStuModel.numberId,modifySqlStuModel.ID];
    
    return [_fmdb executeUpdate:updateStr];
}

+ (BOOL)deleteData:(NSInteger)deleteSqlWithId {
    
    NSString *deleteSql = [NSString stringWithFormat:@"DELETE FROM t_stuModel WHERE id = %zd",deleteSqlWithId];
    
    return [_fmdb executeUpdate:deleteSql];
}

@end
